package com.design.patterns.list.flyweight;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取享元实体的工厂类
 * 可设计为：单例简单工厂类
 * @author Wangzhiwen
 */
public class FlyweightFactory {

    private FlyweightFactory() { }

    // 享元对象池
    private static final Map<String,Flyweight> FLYWEIGHT_MAP = new ConcurrentHashMap<>();

    public static Flyweight getFlyweight(String internalState){
        // 存在则返回
        if (FLYWEIGHT_MAP.containsKey(internalState)) return FLYWEIGHT_MAP.get(internalState);
        // 不存在则创建在返回
        ConcreteFlyweight concreteFlyweight = new ConcreteFlyweight(internalState);
        FLYWEIGHT_MAP.put(internalState,concreteFlyweight);
        return concreteFlyweight;
    }

    public static int flyweightCount(){
        return FLYWEIGHT_MAP.size();
    }
}
